package okhttp3.image;

import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;

import java.io.FileNotFoundException;
import java.io.PrintStream;

public class DotListener {
    private static PrintStream originalSystemErr;
    private static PrintStream originalSystemOut;
    private int testCount;

    public void executionSkipped(TestIdentifier testIdentifier, String reason) {
        this.printStatus("-");
    }

    private final void printStatus(String s) {
        ++testCount;
        if (testCount % 80 == 0) {
            this.printStatus("\n");
        }
        if (originalSystemErr != null) {
            originalSystemErr.print(s);
        }

    }

    public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
        if (!testIdentifier.isContainer()) {
            switch (testExecutionResult.getStatus()) {
                case FAILED:
                    printStatus("F");
                    break;
                case ABORTED:
                    printStatus("-");
                    break;
                case SUCCESSFUL:
                    printStatus(".");
                    break;
                default:
                    printStatus("F");
                    break;
            }
        }
    }

    public void testPlanExecutionFinished(TestPlan testPlan) {
        if (originalSystemErr != null) {
            originalSystemErr.println();
        }

    }

    public static final void install() {
        originalSystemOut = System.out;
        originalSystemErr = System.err;
        try {
            System.setOut(new PrintStream(""));
        } catch (FileNotFoundException e) {
            e.fillInStackTrace();
        }
        try {
            System.setErr(new PrintStream(""));
        } catch (FileNotFoundException e) {
            e.fillInStackTrace();
        }
    }

    public static final void uninstall() {
        System.setOut(originalSystemOut);
        System.setErr(originalSystemErr);
    }

    public DotListener() {
    }

}
